import { analysisIntent, IntentHandler } from "../core/tool/baseScene";
import { mathType } from "../core/tool/face";
import { UserLevel } from "../shared/face";
import { IntentConfig, IntentHelper } from "../core/tool/intentHelper";
import { staticToInstance } from './base/LegacyServiceAdapter';
import { ModernIntentService } from './ModernIntentService';

/**
 * 意图服务
 * 负责处理用户意图识别和路由的业务逻辑
 */
export class IntentService {
    
    /**
     * 创建意图处理器
     * @param mathType 匹配类型
     * @param mathStr 匹配字符串
     * @param action 动作函数
     * @param self 执行上下文
     * @param isHideMath 是否隐藏匹配
     * @returns 意图处理器
     */
    @staticToInstance(ModernIntentService)
    static createIntentHandler(
        mathType: mathType,
        mathStr: string,
        action: Function,
        self: any,
        isHideMath: boolean = false
    ): IntentHandler {
        return {
            mathType,
            mathStr,
            action,
            self,
            updateTime: Date.now(),
            isHideMath
        };
    }
    
    /**
     * 生成意图处理器键值
     * @param mathType 匹配类型
     * @param mathStr 匹配字符串
     * @returns 键值字符串
     */
    @staticToInstance(ModernIntentService)
    static generateIntentKey(mathType: mathType, mathStr: string): string {
        return `${mathType}-${mathStr}`;
    }
    
    /**
     * 排序意图处理器
     * @param handlers 意图处理器数组
     * @returns 排序后的意图处理器数组
     */
    @staticToInstance(ModernIntentService)
    static sortIntentHandlers(handlers: IntentHandler[]): IntentHandler[] {
        return handlers.sort((a, b) => {
            if (a.mathType === b.mathType) {
                return b.mathStr.length - a.mathStr.length;
            }
            return a.mathType - b.mathType;
        });
    }
    
    /**
     * 注册意图处理器
     * @param mathType 匹配类型
     * @param mathStr 匹配字符串
     * @param action 动作函数
     * @param self 执行上下文
     * @param isHideMath 是否隐藏匹配
     * @param intentHandlers 意图处理器映射
     * @returns 注册结果
     */
    @staticToInstance(ModernIntentService)
    static registerIntentHandler(
        mathType: mathType,
        mathStr: string,
        action: Function,
        self: any,
        isHideMath: boolean = false,
        intentHandlers: Map<string, IntentHandler>
    ): boolean {
        try {
            const key = this.generateIntentKey(mathType, mathStr);
            const handler = this.createIntentHandler(mathType, mathStr, action, self, isHideMath);
            intentHandlers.set(key, handler);
            
            return true;
        } catch (error) {
            console.error('注册意图处理器失败:', error);
            return false;
        }
    }
    
    /**
     * 批量注册意图配置
     * @param intentConfigs 意图配置数组
     * @param registerCallback 注册回调函数
     * @param context 上下文
     * @returns 注册结果
     */
    @staticToInstance(ModernIntentService)
    static batchRegisterIntents(
        intentConfigs: IntentConfig[],
        registerCallback: (mathType: mathType, mathStr: string, action: Function, self: any, isHideMath?: boolean) => void,
        context: any
    ): boolean {
        try {
            IntentHelper.registerIntents(intentConfigs, registerCallback, context);
            return true;
        } catch (error) {
            console.error('批量注册意图失败:', error);
            return false;
        }
    }
    
    /**
     * 删除意图处理器
     * @param mathType 匹配类型
     * @param mathStr 匹配字符串
     * @param intentHandlers 意图处理器映射
     * @returns 删除结果
     */
    @staticToInstance(ModernIntentService)
    static deleteIntentHandler(
        mathType: mathType,
        mathStr: string,
        intentHandlers: Map<string, IntentHandler>
    ): boolean {
        try {
            const key = this.generateIntentKey(mathType, mathStr);
            return intentHandlers.delete(key);
        } catch (error) {
            console.error('删除意图处理器失败:', error);
            return false;
        }
    }
    
    /**
     * 获取基本意图配置
     * @param components 组件映射
     * @returns 意图配置数组
     */
    @staticToInstance(ModernIntentService)
    static getBasicIntentConfigs(components: any): IntentConfig[] {
        return [
            // 背包相关指令
            { command: '背包', action: 'client_main', mathType: mathType.完全匹配, component: components.bag, isHideMath: true },
            { command: '血统', action: 'client_main', mathType: mathType.完全匹配, component: components.talent, isHideMath: true },
            
            // 装备栏相关指令
            { command: '装备', action: 'client_main', mathType: mathType.完全匹配, component: components.equip, isHideMath: true },
            
            // 技能相关指令
            { command: '技能', action: 'client_skill', mathType: mathType.完全匹配, component: components.rpg, isHideMath: true },
            { command: '基础指令', action: 'client_menu', mathType: mathType.完全匹配, component: components.base },
            { command: '更新日志', action: 'updateLog', mathType: mathType.完全匹配, component: components.intent },
            { command: '属性', action: 'client_lookAtt', mathType: mathType.完全匹配, component: components.rpg, isHideMath: true },

            
            // 随从相关指令
            { command: '宠物', action: 'client_main', mathType: mathType.完全匹配, component: components.follow, isHideMath: true },
            

            { command: '签到', action: 'client_sign', mathType: mathType.完全匹配, component: components.sign, isHideMath: true },
        ];
    }
    /**
     * 检查管理员权限
     * @param userLevel 用户级别
     * @returns 是否有管理员权限
     */
    @staticToInstance(ModernIntentService)
    static hasAdminPermission(userLevel: UserLevel): boolean {
        return userLevel === UserLevel.开发者;
    }
    
    /**
     * 创建管理员意图配置
     * @param adminComponent 管理员组件
     * @returns 管理员意图配置
     */
    @staticToInstance(ModernIntentService)
    static createAdminIntentConfig(adminComponent: any): IntentConfig {
        return {
            command: '管理员',
            action: 'client_main',
            mathType: mathType.完全匹配,
            component: adminComponent
        };
    }
    
    /**
     * 获取意图处理器统计信息
     * @param intentHandlers 意图处理器映射
     * @returns 统计信息
     */
    @staticToInstance(ModernIntentService)
    static getIntentHandlerStats(intentHandlers: Map<string, IntentHandler>): {
        totalHandlers: number;
        handlersByType: { [key: string]: number };
        componentStats: { [key: string]: number };
    } {
        const stats = {
            totalHandlers: intentHandlers.size,
            handlersByType: {} as { [key: string]: number },
            componentStats: {} as { [key: string]: number }
        };
        
        intentHandlers.forEach((handler, key) => {
            // 按类型统计
            const typeKey = mathType[handler.mathType];
            stats.handlersByType[typeKey] = (stats.handlersByType[typeKey] || 0) + 1;
            
            // 按组件统计
            const componentName = handler.self.constructor.name;
            stats.componentStats[componentName] = (stats.componentStats[componentName] || 0) + 1;
        });
        
        return stats;
    }
    
    /**
     * 清除所有意图处理器
     * @param intentHandlers 意图处理器映射
     */
    @staticToInstance(ModernIntentService)
    static clearAllIntentHandlers(intentHandlers: Map<string, IntentHandler>): void {
        intentHandlers.clear();
    }
    
    /**
     * 验证意图配置
     * @param config 意图配置
     * @returns 验证结果
     */
    @staticToInstance(ModernIntentService)
    static validateIntentConfig(config: IntentConfig): {
        valid: boolean;
        message: string;
    } {
        if (!config.command || config.command.trim() === '') {
            return {
                valid: false,
                message: '意图指令不能为空'
            };
        }
        
        if (!config.action || config.action.trim() === '') {
            return {
                valid: false,
                message: '意图动作不能为空'
            };
        }
        
        if (!config.component) {
            return {
                valid: false,
                message: '意图组件不能为空'
            };
        }
        
        return {
            valid: true,
            message: '意图配置有效'
        };
    }
    
} 